#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>

using namespace std;

void SetNoBlock(int fd)
{
    int f1 = fcntl(fd, F_GETFL);
    if (f1 < 0)
    {
        perror("fctnl");
        return;
    }

    fcntl(fd, F_SETFL, f1 | O_NONBLOCK);
    cout << " set " << fd << " nonblock done" << endl;
}

int main()
{
    SetNoBlock(0);
    char buff[1024];
    sleep(1);

    while (true)
    {
        // cout << "please enter@ ";
        // fflush(stdout);
        ssize_t n = read(0, buff, sizeof(buff));
        if (n > 0)
        {
            buff[n - 1] = 0;
            cout << "echo:" << buff << endl;
        }
        else if (n == 0)
        {
            cout << "read finish" << endl;
            break;
        }
        else if (n < 0)
        {
            // 非阻塞，底层没有就绪,recv/read/write/send,返回值出错返回
            // 怎么区分 a.真的出错 b.底层没有就绪,通过errno
            if (errno == EWOULDBLOCK)
            {
                cout << "fd not ready, try again" << endl;
                // do other thing;
            }
            else
            {
                cerr << "read error," << "error str:" << errno << "," << strerror(errno) << endl;
                sleep(1);
            }
        }
    }

    return 0;
}